package com.zebra.remoting;

import com.zebra.remoting.util.RemotingUtil;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import io.netty.channel.ChannelHandler.Sharable;

/**
 * 关闭空闲连接
 * @author SK
 */
@Sharable
public class HeartbeatServerHandler extends ChannelDuplexHandler {
    private static final InternalLogger logger = InternalLoggerFactory.getInstance(HeartbeatServerHandler.class);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object event) throws Exception {
        if (event instanceof IdleStateEvent) {
            try {
                logger.error("Channel close By: Heartbeat Broken links: {}", RemotingUtil.channelToString(ctx.channel()));
                ctx.close();
            } catch (Exception e) {
                logger.error("Exception caught when closing connection in ServerIdleHandler.", e);
            }
        } else {
            super.userEventTriggered(ctx, event);
        }
    }

}
